import React, { useEffect, useState, Component, useRef } from 'react';
import { fetchSync, request } from '@/utils/request';
import { history, Link } from 'umi';
import { connect, router } from 'dva';

import enUS from 'antd/es/locale/en_US';
import {
    Menu, Switch, Divider, Checkbox, Button, Row, Col, Tooltip, notification, Skeleton, Avatar, DatePicker, Descriptions, FloatButton, Badge,
    Form, Modal, Select, Tree, Icon, Radio, Table, Tag, Pagination, Input, Space, message, Card, Tabs, Collapse, Image, ConfigProvider
} from 'antd';
import { MailOutlined, AppstoreOutlined, SettingOutlined, AudioOutlined, UserOutlined, ArrowRightOutlined, ArrowLeftOutlined, HeartOutlined } from '@ant-design/icons';

import 'mapbox-gl/dist/mapbox-gl.css';
import styles from './activityDetail.less';
import { getUserId, getUserName } from '@/utils/loginAssert';
import moment from 'moment';

export default (props) => {
    const [activity, setActivity] = useState(null);
    const [id, setId] = useState('');
    const [isJoin, setIsJoin] = useState(false)

    const [items, setItems] = useState([])

    //初始函数
    useEffect(async () => {
        //此处编写 组件挂载之后和组件重新渲染之后执行的代码
        // qu_data = await fetchSync('/api/fangxun/qu/findAll')
        const id = history.location.search.split('=')[1];
        setId(id)
        initData(id)
        return () => {
            //此处编写 组件即将被卸载前执行的代码
        }
        // 4、若传值，但是传的是空数组 []，则表示该useEffect里的内容仅会在“挂载完成后和组件即将被卸载前”执行一次；
    }, [])

    const initData = (id) => {
        if (!id) return;
        request('/api/joy/activity/findById/' + id, {
            method: 'get'
        }).then(res => {
            console.log(res)
            if (res.success && res.data) {
                setActivity(res.data)
                let data = { ...res.data }
                delete data.id;
                delete data.userId;

                let _items = Object.keys(data).map(key => {
                    if (key === 'base64Images') {
                        return {
                            label: 'images',
                            children: <div style={{ display: 'flex', flexWrap: 'wrap' }}>
                                {
                                    res.data[key].map((it, key) => {
                                        return <Image key={key} src={it} width={80} height={60} />
                                    })
                                }
                            </div>
                        }
                    } else if (key === 'userName') {
                        return {
                            label: key,
                            children: <div>{res.data[key]} {res.data[key] !== getUserName() ? <Button type="primary" shape="circle" icon={<HeartOutlined />} onClick={() => follow(res.data['userId'])} ></Button> : ''}</div>,
                        }
                    } else if (key === 'userNames') {
                        return {
                            label: 'Participants',
                            children: <div style={{ display: 'flex', flexWrap: 'wrap' }}>
                                {
                                    res.data[key]?.map((it, key) => {
                                        return <Tag key={key} color="#108ee9">{it}</Tag>
                                    })
                                }
                            </div>
                        }
                    } else {
                        return {
                            label: key,
                            children: res.data[key],
                        }
                    }
                })

                setItems(_items)
                setIsJoin(res.data['userNames']?.includes(getUserName()))
            }
        })
    };


    const follow = async (id) => {
        const res = await fetchSync('/api/user/findUserById/' + id)
        if (res.success) {
            let follows = res.data.follows || [];
            if (follows.includes(getUserName())) {
                message.warning('existed')
            } else {
                follows.push(getUserName())
                request('/api/user/update', {
                    method: 'POST',
                    data: {
                        id,
                        follows:follows
                    }
                }).then(async res => {
                    console.log(res)
                    if (res.success) {
                        message.info('follow success')

                        const res2 = await fetchSync('/api/user/findUserById/' + getUserId())
                        let friendIds = res2.data.friendIds || [];
                        if (friendIds.includes(id)) {
                        } else {
                            friendIds.push(id)
                            request('/api/user/update', {
                                method: 'POST',
                                data: {
                                    id: getUserId(),
                                    friendIds
                                }
                            }).then(res => {
                                console.log(res)
                                if (res.success) {
                                    message.info('update friend success')
                                    let user = JSON.parse(sessionStorage.getItem("user"))
                                    sessionStorage.setItem("user", JSON.stringify({...user, friendIds}));
                                }
                            })
                        }
                    }
                })
            }

        }

    }

    const joinHandle = () => {
        console.log(isJoin)
        if (moment(activity['activityTime']) - moment() < 0) {
            message.warning('Activity Timed out !')
            return;
        }
        let userNames = activity.userNames || []
        if (isJoin) { //remove
            userNames = userNames.filter(user => user !== getUserName())
        } else {
            userNames.push(getUserName())
        }
        console.log(userNames)
        request('/api/joy/activity/update', {
            method: 'POST',
            data: {
                id,
                userNames
            }
        }).then(res => {
            console.log(res)
            if (res.success) {
                // setIsJoin(!isJoin)
                initData(id)
            }

        })
    }

    return (
        <div className={styles.container}>

            <div className={styles.header}>
                <Link to="/runjoy">
                    <Button type="link" style={{ marginTop: 12 }} shape="circle" icon={<ArrowLeftOutlined style={{ color: '#fff', fontSize: 36 }} />} />
                </Link>
                <span className={styles.title}>
                    Activty Details
                </span>
            </div>
            <br />

            <Descriptions
                title=""
                bordered
                column={{
                    xs: 1,
                    sm: 1,
                    md: 3,
                    lg: 3,
                    xl: 4,
                    xxl: 4,
                }}
                items={items}
            />

            <FloatButton.Group
                shape="circle"
                style={{
                    right: 12,
                }}
            >
                {/* <FloatButton icon={<QuestionCircleOutlined />} /> */}
                <FloatButton description='JOIN' type={!isJoin ? 'default' : 'primary'} onClick={joinHandle} />
                <FloatButton.BackTop visibilityHeight={0} />
            </FloatButton.Group>
        </div>
    );
}
